package com.ives.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 陈玉林
 * @desc TODO
 * @date 2020/6/29 14:38
 */
public class RedisLockTest {
    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(3);
        service.execute(new MyTask());
        service.execute(new MyTask());
        service.execute(new MyTask());
        service.shutdown();
    }

    private static class MyTask implements Runnable {

        @Override
        public void run() {
            RedisLock redisLock = new RedisLock("1");
            boolean lock = redisLock.lock();
            if (lock) {
                System.out.println(String.format("线程【%s】获取锁成功!", Thread.currentThread().getId()));
                try {
                    //模拟业务处理时间超过锁超时时间，使用守护线程为锁续命
                    System.out.println(String.format("线程【%s】模拟阻塞40秒!", Thread.currentThread().getId()));
                    Thread.sleep(40000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    redisLock.unLock();
                }
            } else {
                System.out.println(String.format("线程【%s】获取锁失败!", Thread.currentThread().getId()));
            }
        }
    }
}
